#include "step_motor.h"
#include "task.h"
#include "STC89C5xRC.H"

/* define your step motor IO start */
sbit STEP_MOTOR_A = P3 ^ 4;
sbit STEP_MOTOR_B = P3 ^ 5;
sbit STEP_MOTOR_C = P3 ^ 6;
sbit STEP_MOTOR_D = P3 ^ 7;
/* define your step motor IO end */

/* define your data start */
static volatile step_motor_t step_motoe_panel = {0, 0, 1};
/* define your data end */

/**
 * @brief step_motor_demo
 *
 * @param A[0/1]
 * @param B[0/1]
 * @param C[0/1]
 * @param D[0/1]
 */
static void step_motor_demo(bool A, bool B, bool C, bool D)
{
    STEP_MOTOR_A = A;
    STEP_MOTOR_B = B;
    STEP_MOTOR_C = C;
    STEP_MOTOR_D = D;
}

/**
 * @brief step_motor_stop
 *
 */
static void step_motor_stop(void)
{
    STEP_MOTOR_A = 0;
    STEP_MOTOR_B = 0;
    STEP_MOTOR_C = 0;
    STEP_MOTOR_D = 0;
}

/**
 * @brief step_motor_correct_number
 *
 * @param number
 */
static void step_motor_correct_number(uint8_t number)
{
    switch (number)
    {
    case 0:
        step_motor_demo(1, 0, 0, 1);
        break;
    case 1:
        step_motor_demo(0, 0, 0, 1);
        break;
    case 2:
        step_motor_demo(0, 0, 1, 1);
        break;
    case 3:
        step_motor_demo(0, 0, 1, 0);
        break;
    case 4:
        step_motor_demo(0, 1, 1, 0);
        break;
    case 5:
        step_motor_demo(0, 1, 0, 0);
        break;
    case 6:
        step_motor_demo(1, 1, 0, 0);
        break;
    case 7:
        step_motor_demo(1, 0, 0, 0);
        break;
    default:
        step_motoe_panel.step_tick = 0;
        step_motor_stop();
        break;
    }
}

/**
 * @brief step_motor_anti_number
 *
 * @param number
 */
static void step_motor_anti_number(uint8_t number)
{
    switch (number)
    {
    case 0:
        step_motor_demo(1, 0, 0, 0);
        break;
    case 1:
        step_motor_demo(1, 1, 0, 0);
        break;
    case 2:
        step_motor_demo(0, 1, 0, 0);
        break;
    case 3:
        step_motor_demo(0, 1, 1, 0);
        break;
    case 4:
        step_motor_demo(0, 0, 1, 0);
        break;
    case 5:
        step_motor_demo(0, 0, 1, 1);
        break;
    case 6:
        step_motor_demo(0, 0, 0, 1);
        break;
    case 7:
        step_motor_demo(1, 0, 0, 1);
        break;
    default:
        step_motoe_panel.step_tick = 0;
        step_motor_stop();
        break;
    }
}

/**
 * @brief step_motor_struct_panel
 *
 * @return step_motoe_panel
 */
step_motor_t *step_motor_struct_panel(void)
{
    return &step_motoe_panel;
}

/**
 * @brief step_motor_interrupt
 *
 */
void step_motor_interrupt(void)
{
    if (step_motoe_panel.step_angle == 0)
    {
        step_motor_stop();
    }
    else
    {
        step_motoe_panel.step_tick++;
        step_motoe_panel.step_angle--;
        if (step_motoe_panel.step_direct)
        {
            step_motor_correct_number(step_motoe_panel.step_tick); /* 顺时针 */
        }
        else
        {
            step_motor_anti_number(step_motoe_panel.step_tick); /* 逆时针 */
        }
    }
}